package routers

import (
	"github.com/gin-gonic/gin"
	"log"
	"my_music_server/common"
	"my_music_server/config/middle_ware"
	"my_music_server/controller"
	"net/http"
	"runtime"

	"github.com/swaggo/files"          // swagger embed files
	gs "github.com/swaggo/gin-swagger" // gin-swagger middleware
	_ "my_music_server/docs"
)

// 全局异常中间件
func GlobalExceptionHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		//fmt.Println("exception in......")
		defer func() {
			err := recover()
			if err != nil {
				c.JSON(http.StatusInternalServerError, common.Error().SetMessage(err.(string)))
				log.Default().Panic(err)
			}
		}()
		//in 【类spring的环绕通知】
		c.Next() //调用后续的处理函数
		//out 【类spring的环绕通知】
		//fmt.Println("exception out......")
	}
}

func SetupRouters() *gin.Engine {
	if runtime.GOOS == "windows" {
		gin.ForceConsoleColor()
	}
	//创建一个gin引擎实例
	router := gin.Default()
	//token认证da【注意配置顺序GlobalExceptionHandler必须在最前】
	router.Use(GlobalExceptionHandler(), middle_ware.JwtTokenMiddleWare())
	router.StaticFile("/favicon.ico", "./resources/favicon.ico")

	//swagger
	router.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))

	//user
	router.GET("/login", controller.Login)
	router.GET("/test", controller.MyTest)
	router.POST("/register", controller.Register)

	//song
	songGroup := router.Group("/song")
	{
		songGroup.GET("/all", controller.GetSongList)
	}

	//file
	fileGroup := router.Group("/file")
	{
		fileGroup.POST("/upload", controller.UploadFile)
	}
	return router
}
